#!/usr/bin/perl
use strict;
use warnings;

# wmono@cs.ubc.ca 2010 03 02
# BSD (3 clause) license for this file

$|++;

use List::Util qw(shuffle);

open PHRASES, 'phrases2.txt' or die "failed to open phrases $!";

my @phrases;
while (<PHRASES>) {
    chomp;
    next if $_ =~ m/[^a-z ]/;
    next if $_ =~ m/\S{8}/;
    push @phrases, $_;
}

close PHRASES;




my @sets;
my $phrases_per_set = 20;
my $target_setlength = 0;

SET:
while (@sets < 8) {
    @phrases = shuffle(@phrases);

    my @set;
    push @sets, \@set;

    my $setlength = 0;

    for (1..$phrases_per_set) {
        my $phrase = pop @phrases;
        push @set, $phrase;
        $setlength += length $phrase;
    }

    if ($target_setlength == 0) {
        $target_setlength = $setlength;
    }

    my $attempts = 0;

    CORRECTION:
    while ($setlength != $target_setlength) {
        $attempts++;

        my $old_phrase = shift @set;
        push @phrases, $old_phrase;
        $setlength -= length $old_phrase;

        my $target_phrase_length = $target_setlength - $setlength;
        for (my $ix = 0; $ix < length @phrases; $ix++) {
            if (length($phrases[$ix]) == $target_phrase_length) {
                my $phrase = splice(@phrases, $ix, 1);
                push @set, $phrase;
                $setlength += length $phrase;
                last CORRECTION;
            }
        }

        my $phrase = splice(@phrases, int rand(scalar @phrases), 1);
        push @set, $phrase;
        $setlength += length $phrase;

        if ($attempts > 100*$phrases_per_set) {
            @sets = ();
            next SET;
        }
    }

    print "set ", scalar(@sets), ": length $setlength\n\n";
}


foreach (@sets) {
    my @set = shuffle(@{$_});

    print "====== Set X ======\n";
    foreach (@set) {
        print "$_\n";
    }
    print "\n";
}

